<?php
// +----------------------------------------------------------------------
// | Description: Api基础类，验证权限
// +----------------------------------------------------------------------
// | Author:
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\facade\Cache;
use think\facade\Db;
use app\common\controller\Common;


class ApiCommon extends Common
{
    public function initialize()
    {
        parent::initialize();


        /*获取头部信息*/
        $request   = request();
        $header    = $request->header();
        $authKey   = isset($header['auth-key']) && $header['auth-key'] ? trim($header['auth-key']) : '';
        $sessionId = isset($header['session-id']) && $header['session-id'] ? trim($header['session-id']) : '';
        $paramArr  = $request->param();
        //$platform = isset($header['platform']) && $header['platform'] ? '_'.$header['platform'] : ''; //请求平台(mobile,ding)
        $cache     = Cache::get('auth:' . $authKey);

        // 校验sessionid和authKey
        if (empty($sessionId) || empty($authKey) || empty($cache)) {
            header('Content-Type:application/json; charset=utf-8');
            $dataTime=date('H:i',time());
            exit(json_encode([
                'code' => 401,
                'data' => ['extra' => 1, 'extraTime' => $dataTime],
                'msg'  => '你的账号在其他设备登录，请重新登录!'
            ]));
        }
        //登录有效时间
        $cacheConfig = config('cache');
        $loginExpire = !empty($cacheConfig['expire']) ? $cacheConfig['expire'] : 86400 * 30;

        // 检查账号有效性
        $this->userInfo = $cache['userInfo']->toArray();
        $map = [
            ['id', '=', $this->userInfo['id']],
            ['status', 'in', '1,2']
        ];
        $userData = Db::name('admin_user')->where($map)->find();
        if (!$userData) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code'=>401, 'data' => [], 'msg'=>'帐号已被禁用']));
        }
        session('user_id', $this->userInfo['id']);
        // 更新缓存
        Cache::set('auth:'.$authKey, $cache, $loginExpire);
    }
}
